#!/bin/bash

kernel_dir=/srv/fai/tftp
repo_dir=/srv/www

list=""

append() {
  local release=$1
  local kernel=$2
  local releaseou=$(echo "$release" | sed -r '/\//s%(.*)/(.*)%\2,ou=\1%')
  local dn="cn=$kernel,ou=kernels,ou=$releaseou,ou=fai"
  local listentry="dn: $dn
cn: $kernel
release: $release

"
      # Eliminate duplicates
  echo "$list" | grep -qF "$dn" || list="${list}${listentry}"
}


for kernel in $(find "$kernel_dir" -name "vmlinuz-*" -printf '%f\n') ; do
  version=${kernel##vmlinuz-}
  for packagesbz2 in $(find "$repo_dir" -not -path "*/.temp/*" -path "*/dists/*/binary-i386/Packages.bz2" -print) ; do
    bzcat "$packagesbz2" | grep -q "^Package: linux-image-$version"'$'
    test $? = 0 && {
      release=${packagesbz2##*/dists/}
      release=${release%%/binary-i386/*}
      release=${release%/*}
      # for each release that has at least 1 supported kernel we add a default option
      append $release default
      # now add the kernel we just found
      append $release $kernel
    }
  done
done

echo "$list"
